//
//  CRCommentViewController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/28.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRSpaceCommentViewController.h"
#import "CRSpaceCell.h"
#import "CRSpaceFrame.h"
#import "CRCommentTextField.h"
#import "CRSpaceCommentCell.h"
#import "CRSpaceComment.h"
#import "CRSpace.h"
#import "CRTool.h"
#import "MJRefresh.h"
#import "MBProgressHUD+MJ.h"


@interface CRSpaceCommentViewController () <UITableViewDelegate, UITableViewDataSource, CRCommentTextFieldDelegate, UITextFieldDelegate>

/**
 *  评论条
 */
@property (nonatomic, weak) CRCommentTextField *comment;

/**
 *  存放评论模型的数组
 */
@property (nonatomic, strong) NSArray *comments;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation CRSpaceCommentViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置tableview
    [self setupTableView];
    
    // 添加下面的评论条
    [self setupComment];
    
    self.title = @"评论墙";
    
    
    // 监听键盘弹出的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    // 注册cell
    [self.tableView registerClass:[CRSpaceCell class] forCellReuseIdentifier:@"spaceCell"];
    [self.tableView registerClass:[CRSpaceCommentCell class] forCellReuseIdentifier:@"cell"];
    
    // 添加刷新控件
    [self setupRresh];
    // 进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


}

// 添加刷新控件
- (void)setupRresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = header;
}


#pragma mark - 下拉刷新的方法
- (void)headerRefresh
{
    // 取得评论内容
    [CRTool getallCommentsWithObjectId:self.frameModel.space.objectId withblock:^(NSArray *data) {
        
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dict in data) {
            CRSpaceComment *comment = [CRSpaceComment commentWithDict:dict];
            [array addObject:comment];
        }
        self.comments = array;
        // 刷新界面
        [self.tableView reloadData];
        // 停止刷新
        [self.tableView.mj_header endRefreshing];
        // 显示提示信息
        [self showCommentMessageWithNumber:data.count];
    }];

}


- (void)setupTableView
{
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    CGFloat screnW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screnH = [UIScreen mainScreen].bounds.size.height;
    self.tableView.frame = CGRectMake(0, 0, screnW, screnH - 44);
    [self.view addSubview:self.tableView];
}


#pragma mark - 添加下面的评论条
- (void)setupComment
{
    CRCommentTextField *comment = [[CRCommentTextField alloc] init];
    comment.delegate = self;
    // 改键盘的右下角发送按钮
    comment.returnKeyType = UIReturnKeySend;
    // 设置评论条的代理
    comment.commentDelegate = self;
    comment.placeholder = @"请输入评论...";
    CGFloat screnH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screnW = [UIScreen mainScreen].bounds.size.width;
    comment.frame = CGRectMake(0, screnH - 44, screnW, 44);
    self.comment = comment;
    [self.view addSubview:comment];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1 + self.comments.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        CRSpaceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"spaceCell" forIndexPath:indexPath];
        cell.spaceFrame = self.frameModel;
        return cell;
        
    }
        CRSpaceCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.comment = self.comments[indexPath.row - 1];
        return cell;
    
 
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return self.frameModel.cellHeight;
    } else {
        
        return [CRSpaceCommentCell hieghtForCell];
      
        
    }
    
}

#pragma mark - 点击键盘右下角发送按钮的代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //--
    [self commentTextFieldDidClickButton:nil andtextField:self.comment];
    self.comment.text = @"";
    [self.view endEditing:YES];
    
    return YES;
}


#pragma mark - 监听键盘弹出和隐藏的通知

// 键盘即将显示的时候调用
- (void)keyboardWillShow:(NSNotification *)notification
{
    // 1. 取出键盘的frame
    CGRect keyboardF = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2. 取出键盘弹出的时间
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 3. 执行动画
    [UIView animateWithDuration:duration animations:^{
        self.comment.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height);
    }];
}

//   键盘即将退出的时候调用
- (void)keyboardWillHide:(NSNotification *)notification
{
    // 2. 取出键盘弹出的时间
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 3. 执行动画
    [UIView animateWithDuration:duration animations:^{
        self.comment.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - 界面滑动结束键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - 评论条中发送按钮的代理方法--在此方法中处理评论的内容(上传到服务器)
- (void)commentTextFieldDidClickButton:(UIButton *)button andtextField:(UITextField *)textField
{
   
    // 上传评论到服务器
    AVUser *user = [AVUser currentUser];
    AVFile *file = user[@"icon"];
    // 当前用户的头像url
    NSString *iconUrl = file.url;
    // 当前用户的username
    NSString *username = user.username;
    // 当前用户的评论内容
    NSString *content = textField.text;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:iconUrl forKey:@"iconUrl"];
    [dict setValue:username forKey:@"username"];
    [dict setValue:content forKey:@"content"];
    
    // 上传
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"objectId" equalTo:self.frameModel.space.objectId];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        // 找到那条空间内容
        NSArray *tempArray = object[@"Usercontent"];
        // 如果没有那个字段--就先创建--(表被清空了还能用)
        if (tempArray == nil) {
            [object setObject:@[] forKey:@"Usercontent"];
            [object save];
            tempArray = object[@"Usercontent"];
        }
        
        
        // 计算是第几楼
        long count = tempArray.count;
        [dict setValue:[NSString stringWithFormat:@"%ld", count+1] forKey:@"position"];
        NSMutableArray *muTempArray = [NSMutableArray arrayWithArray:tempArray];
        [muTempArray addObject:dict];
        
        // 保存到本地模型
        CRSpaceComment *comment = [CRSpaceComment commentWithDict:dict];
        NSMutableArray *muArray = [NSMutableArray arrayWithArray:self.comments];
        [muArray addObject:comment];
        self.comments = muArray;
        [self.tableView reloadData];
        
        [object setObject:muTempArray forKey:@"Usercontent"];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            
            NSLog(@"===============================%@", error);
            [MBProgressHUD showSuccess:@"评论成功"];
        }];
    }];
    
    
   
    
   
}

// 显示一个提示信息
- (void)showCommentMessageWithNumber:(NSInteger)count
{
    CGFloat W = [UIScreen mainScreen].bounds.size.width;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, W - 40 , 44)];
    label.backgroundColor = [UIColor colorWithRed:1.000 green:0.442 blue:0.094 alpha:1.000];
    label.textAlignment = NSTextAlignmentCenter;
    if (count == 0) {
        label.text = @"快来抢个沙发吧";
    } else {
        label.text = [NSString stringWithFormat:@"为您刷新了%ld条评论", count];
    }
    [self.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    [UIView animateWithDuration:2.0 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, 45);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:2.0 animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
    
}
@end










